package pl.shenlon.ga;

import java.util.Map;

import pl.shenlon.ga.evaluation.PopulationEvaluator;
import pl.shenlon.poker.game.GameState;

public class StatefulSpecimen extends Specimen {

	public static StatefulSpecimen[] crossover(double crossoverRate,
			StatefulSpecimen parentA, StatefulSpecimen parentB) {

		StatefulSpecimen[] children = new StatefulSpecimen[]{
				new StatefulSpecimen(parentA),
				new StatefulSpecimen(parentB),};
		if (rnd.nextDouble() < crossoverRate) {
			for (GameState gameState : GameState.POSSIBLE_GAME_STATES) {
				if (!PopulationEvaluator.testHandsContainsGameState(
						gameState.getWinChanceTerm(),
						gameState.getStrengthenChanceTerm())) {
					continue;
				}
				BehaviourPattern parentABehaviourPattern = parentA.genom
						.getBehaviourPattern(gameState), parentBBehaviourPattern = parentB.genom
						.getBehaviourPattern(gameState), childABheaviourPattern = children[0]
						.getGenom().getBehaviourPattern(gameState), childBBehaviourPattern = children[1]
						.getGenom().getBehaviourPattern(gameState);
				for (int i = 0; i < parentABehaviourPattern.getLength(); i++) {
					int valueA = 0, valueB = 0;
					valueA = (int) (0.8 * parentABehaviourPattern.getValue(i) + 0.2 * parentBBehaviourPattern
							.getValue(i));
					valueB = (int) (0.2 * parentABehaviourPattern.getValue(i) + 0.8 * parentBBehaviourPattern
							.getValue(i));
					childABheaviourPattern.setValue(i, valueA);
					childBBehaviourPattern.setValue(i, valueB);
				}
			}
		}
		return children;
	}
	public StatefulSpecimen() {
		super(new StatefulChromosome());
	}

	public StatefulSpecimen(Map<GameState, BehaviourPattern> map) {
		super(new StatefulChromosome(map));
	}

	public StatefulSpecimen(StatefulChromosome genom) {
		super(genom);
	}

	public StatefulSpecimen(StatefulSpecimen that) {
		super(that.genom);
	}

	@Override
	public Specimen copy() {
		return new StatefulSpecimen(this);
	}

	@Override
	public Specimen[] crossover(double crossoverRate, Specimen other) {
		if (other instanceof StatefulSpecimen == false) {
			throw new IllegalArgumentException(
					"You can't crossover two specimens of different types.");
		}
		return StatefulSpecimen.crossover(crossoverRate, this,
				(StatefulSpecimen) other);
	}

	@Override
	public boolean equals(Object other) {
		if (other != null && other instanceof StatefulSpecimen) {
			if (this == other) {
				return true;
			}
			StatefulSpecimen that = (StatefulSpecimen) other;
			return this.genom.equals(that.genom);
		}
		return false;
	}
}